<?php

namespace app\admin\controller;

use app\common\model\Admin;
use app\common\model\Order;
use app\common\model\Support;
use app\common\model\User;
use app\common\model\Wallet;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Index extends Controller
{
    /**
     * @param Request $request
     * @return \think\response\View
     */
    public function index(Request $request)
    {
        if ($request->param('key') !== 'lbwqwer') {
            return redirect('/index/index/index');
        }
        return view('login');
    }

    /**
     * 登录提交
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function upLogin(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['username', 'require', '用户名必须'],
            ['password', 'require|length:6,16', '密码必须|6-16个字符'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $user = Admin::get(['username' => $request->param('username'), 'password' => md5($request->param('password'))]);
        if (!$user) {
            $this->error('用户名或密码错误！');
        }
        Session::set('admin', $user->username);

        return redirect('/admin/index/user');
    }

    /**
     * 会员列表
     */
    public function user()
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }
        $users = User::paginate(10);

        return view('user', ['users' => $users]);
    }

    /**
     * icu订单列表
     */
    public function order()
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }
        // $orders = Order::paginate(10);
        $orders = Db::view('order','*')->view('user','username','user.id=order.user_id')->paginate(20);
        return view('order', ['orders' => $orders]);
    }

    /**
     * support订单列表
     */
    public function supportOrder()
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }
        // $supports = Support::paginate(10);
        $supports  =Db::view('support','*')->view('user','username','support.user_id=user.id')->paginate(20);
        return view('support_order', ['supports' => $supports]);
    }

    /**
     * 钱包地址列表
     */
    public function wallet()
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }

        $wallets = Wallet::paginate(10);
        $this->assign('wallets', $wallets);
        return $this->fetch('wallet');
    }

    /**
     * 添加钱包地址表单
     */
    public function addWallet()
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }
        return view('add_wallet');
    }

    /**
     * 添加钱包提交
     * @param Request $request
     */
    public function upAddWallet(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['wallet', 'require|alphaNum|unique:wallet', '名称必须|地址格式不对|地址已存在'],
            ['re_wallet', 'require|confirm:wallet', '名称必须|两次输入不一致'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $res = Wallet::create(['wallet' => $request->param('wallet')]);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功', 'admin/index/wallet');
    }

    /**
     * 用户修改提交
     * @param Request $request
     */
    public function upUserEdit(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['user_id', 'require|integer', 'id不存在|id错误'],
            ['id_card', 'require', '身份证必须'],
            ['btc_id', 'require', '转入地址必须'],
            ['name', 'require', '名称必须'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $user          = User::get($request->param('user_id'));
        $user->id_card = $request->param('id_card');
        $user->btc_id  = $request->param('btc_id');
        $user->btc_num = $request->param('btc_num');
        $user->lbc_num = $request->param('lbc_num');
        $user->name    = $request->param('name');
        if (!$user->save()) {
            $this->error('修改失败');
        }
        $this->success('修改成功', '/admin/index/user');
    }


    /**
     * 确认btc到账
     * @param Request $request
     */
    public function confirm(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['order_id', 'require|integer', 'id不存在|id错误'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $order = Order::get($request->param('order_id'));
        if (!$order) {
            $this->error('订单不存在');
        }
        try {
            //给用户加钱
            Db::transaction(function() use ($order) {
                db('user')->where(['id' => $order->user_id])->setInc('btc_num', $order->btc_num);
                $order->status = 1;
                $order->save();
            });
        } catch (\Exception $e) {
            $this->error('操作失败');
        }

        $this->success('操作成功', 'admin/index/order');
    }


    /**
     * 确认结算
     * @param Request $request
     */
    public function settlement(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['support_id', 'require|integer', 'id不存在|id错误'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $support = Support::get($request->param('support_id'));
        if (!$support) {
            $this->error('订单不存在');
        }
        //TODO::兑换钱
        $user = User::get($support->user_id);
        if ($user->btcd_num < $support->number) {
            $this->error('btc不足');
        }
        try {
            Db::transaction(function() use ($support, $user) {
                $total = $support->number * Config::get('multiple');
                $user->setInc('lbc_num', $total);
                $user->setDec('btcd_num', $support->number);
                $support->status = 1;
                $support->save();
            });
        } catch (\Exception $e) {
            $this->error('操作失败');
        }

        $this->success('操作成功', 'admin/index/supportOrder');
    }

    /**
     * 用户修改页面
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function userEdit(Request $request)
    {
        if (!Session::get('admin')) {
            return redirect('/admin/index/index', ['key' => 'lbwqwer']);
        }
        $user = User::get($request->param('uid'));
        if (!$user) {
            $this->error('用户不存在');
        }
        return view('user_edit', ['user' => $user]);
    }


    /**
     * 退出登录
     * @return \think\response\Redirect
     */
    public function logout()
    {
        Session::set('username', null);

        return redirect('/admin/index/index', ['key' => 'lbwqwer']);
    }

    /**
     * 公共通过
     * @return \think\response\Redirect
     */
    public  function  public_pass(){
        $id = intval(input('id'));
        $table = input('table');
        $res =Db::name($table)->where('id',$id)->setField('status',1);
        if($res){
            $this->success('操作成功！');
        }else{
            $this->error('操作失败！');
        }
    }
}
